package com.heima.behavior.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.behavior.mapper.ApLikesBehaviorMapper;
import com.heima.behavior.mapper.ApUnlikesBehaviorMapper;
import com.heima.behavior.service.ApArticleRelationService;
import com.heima.behavior.service.ApBehaviorEntryService;
import com.heima.model.behavior.dtos.ApArticleRelationDto;
import com.heima.model.behavior.pojos.ApBehaviorEntry;
import com.heima.model.behavior.pojos.ApLikesBehavior;
import com.heima.model.behavior.pojos.ApUnlikesBehavior;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApArticleRelationServiceImpl implements ApArticleRelationService {

    @Autowired
    ApLikesBehaviorMapper apLikesBehaviorMapper;

    @Autowired
    ApUnlikesBehaviorMapper apUnlikesBehaviorMapper;

    @Autowired
    ApBehaviorEntryService apBehaviorEntryService;

    /**
     * 查询用户点赞,不喜欢,及用户实体id
     * 查询结果{"islike":true,"isunlike":false,"entryId",1}
     * @param dto
     * @return
     */
    @Override
    public Map findApArticleRelation(ApArticleRelationDto dto) {
        //1.定义保存点赞和不喜欢的实体类
        Map map = new HashMap();
        map.put("islike",false);
        map.put("isunlike",false);
        if(dto.getArticleId() == null || dto.getEntryId() == null){
            return map;
        }

        //2.查询行为实体
        ApBehaviorEntry apBehaviorEntry = new ApBehaviorEntry();
        if(dto.getType().intValue() == 0){
            //按照设备ID查询行为实体
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(null,dto.getEntryId());
        }else {
            //按照用户ID查询行为实体
            apBehaviorEntry = apBehaviorEntryService.findByUserIdOrEquipmentId(dto.getEntryId(),null);
        }
            //如果没有查询到行为实体返回空
        if(apBehaviorEntry == null){
            return map;
        }

        //3.根据行为实体ID 及 文章id 查询是否点过赞
        ApLikesBehavior apLikesBehavior = apLikesBehaviorMapper.selectOne(Wrappers.<ApLikesBehavior>lambdaQuery()
                .eq(ApLikesBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApLikesBehavior::getArticleId, dto.getArticleId())
        );
        if(apLikesBehavior != null){
            map.put("islike",true);
        }

        //5.根据行为实体及文章id查询是否点过不喜欢
        ApUnlikesBehavior unlikesBehavior = apUnlikesBehaviorMapper.selectOne(Wrappers.<ApUnlikesBehavior>lambdaQuery()
                .eq(ApUnlikesBehavior::getEntryId, apBehaviorEntry.getId())
                .eq(ApUnlikesBehavior::getArticleId, dto.getArticleId()));
        if(unlikesBehavior != null){
            map.put("isunlike",true);
        }

        //6.返回行为实体ID
        map.put("entryId",apBehaviorEntry.getId());
        return map;
    }
}